package com.sfac.javaSpringBoot.modules.common.service.Impl;

import com.sfac.javaSpringBoot.config.ResourceProperties;
import com.sfac.javaSpringBoot.modules.common.entity.ImageType;
import com.sfac.javaSpringBoot.modules.common.entity.Result;
import com.sfac.javaSpringBoot.modules.common.service.ImageService;
import com.sfac.javaSpringBoot.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ResourceProperties resourceProperties;
    @Value("${artifactId}")
    private String artifactId;

    @Override
    public Result<String> uploadImage(MultipartFile file, String imageTypeName) {
        // 校验：文件是否为空、文件类型、文件尺寸大小
        if (file.isEmpty()){
            return new Result<>(Result.ResultCode.FAILED.code,
                    "File is empty.");
        }
        if (!FileUtil.isImage(file)) {
            return new Result<>(Result.ResultCode.FAILED.code,
                    "Please upload image file.");
        }
        ImageType imageType = ImageType.getImageTypeByName(imageTypeName);
        if (imageType == null) {
            return new Result<>(Result.ResultCode.FAILED.code,
                    "Image type error.");
        }
        if ((file.getSize() / 1024) > imageType.size) {
            return new Result<>(Result.ResultCode.FAILED.code,
                    "Image size exceed range.");
        }

        // 检查目标文件夹是否存在，如果不存在则创建对应的文件夹
        String systemName = System.getProperty("os.name");
        String localPath = systemName.toLowerCase().startsWith("win") ?
                resourceProperties.getWindowLocation() :
                resourceProperties.getLinuxLocation();
        String destFolderPath = String.format("%s%s/%s", localPath, artifactId, imageTypeName);
        File destFolder = new File(destFolderPath);
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }

        //文件重命名
        String originalFilename = file.getOriginalFilename();
        String[] temp = originalFilename.split("\\.");
        String fileName = String.format("%s.%s",
                System.currentTimeMillis(), temp[temp.length - 1]);

        try {
            // 将图片写到目标地址
            String destFilePath = String.format("%s/%s", destFolderPath, fileName);
            File destFile = new File(destFilePath);
            file.transferTo(destFile);

            // 可选：变更图片像素
            FileUtil.changeImageSize(destFilePath, destFilePath, imageType.width, imageType.length);

            // 返回 result，包装图片的相对路径地址
            String relatedPath = String.format("%s%s/%s/%s",
                    resourceProperties.getPath(), artifactId, imageTypeName, fileName);
            return new Result<>(Result.ResultCode.SUCCESS.code,
                    "Upload image success.", relatedPath);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result<>(Result.ResultCode.FAILED.code,
                    "Upload image error.");
        }
    }
}